<template>
  <common-layout id="commonLayout">
    <div class="login">
      <a-form @submit="onSubmit" :form="form">
        <a-tabs size="large" :tabBarStyle="{ textAlign: 'center' }" style="padding: 0 2px">
          <a-tab-pane tab="用户登录" key="1">
            <a-alert
              type="error"
              :closable="true"
              v-show="error"
              :message="error"
              showIcon
              style="margin-bottom: 24px"
            />
            <a-form-item>
              <a-input
                autocomplete="autocomplete"
                size="large"
                placeholder="请输入账号"
                v-decorator="[
                  'loginAccount',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入账户名',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <a-icon slot="prefix" type="user" />
              </a-input>
            </a-form-item>
            <a-form-item>
              <a-input
                size="large"
                placeholder="请输入密码"
                autocomplete="autocomplete"
                type="password"
                v-decorator="[
                  'loginPwd',
                  {
                    rules: [
                      {
                        required: true,
                        message: '请输入密码',
                        whitespace: true,
                      },
                    ],
                  },
                ]"
              >
                <a-icon slot="prefix" type="lock" />
              </a-input>
            </a-form-item>
          </a-tab-pane>
        </a-tabs>
        <div>
          <a-checkbox>自动登录</a-checkbox>
        </div>
        <a-form-item>
          <a-button
            :loading="logging"
            style="width: 100%; margin-top: 24px"
            size="large"
            htmlType="submit"
            type="primary"
            >登录</a-button
          >
        </a-form-item>
      </a-form>
    </div>
  </common-layout>
</template>

<script>
import CommonLayout from '@/layouts/CommonLayout';
import { userService } from '@/services';
import { mapMutations } from 'vuex';
import { loadRoutes } from '@/utils/routerUtil';
import { transListToTree } from '@/utils/util';
import { setAuthorization } from '@/utils/request';

export default {
  name: 'Login',

  components: { CommonLayout },

  data() {
    return {
      logging: false,
      error: '',
      form: this.$form.createForm(this),
    };
  },
  computed: {
    systemName() {
      return this.$store.state.setting.systemName;
    },

    commonLayoutStyle() {
      // console.log(JSON.parse(localStorage.getItem('system-config')));
      const background = JSON.parse(localStorage.getItem('system-config'))['login-background'];
      return {
        'background-image': `url(${background})`,
      };
    },
  },

  methods: {
    ...mapMutations('account', ['setUser']),

    onSubmit(e) {
      e.preventDefault();
      this.form.validateFields((err, values) => {
        if (!err) {
          this.logging = true;
          console.log(values);
          const { loginAccount, loginPwd } = values;
          userService.login({ loginAccount, loginPwd }).then(this.afterLogin);
        }
      });
    },

    afterLogin(res) {
      this.logging = false;

      if (res.code && res.code === '200') {
        const { token, user } = res.data;
        setAuthorization({ token });
        this.setUser(user);

        // 获取路由配置
        userService.getMenu().then(res => {
          console.log('获取路由配置', res);
          // 过滤按钮权限
          const btnList = res.data.menuList.filter(item => item.type === 2);
          localStorage.setItem(process.env.VUE_APP_USER_PERMS, JSON.stringify(btnList));

          // 过滤菜单权限
          const menuList = res.data.menuList.filter(item => item.type !== 2);
          const routesConfig = [
            {
              router: 'root',
              children: [
                {
                  path: 'home',
                  name: '首页',
                  icon: 'home',
                  orderNum: -1,
                  parentId: -1,
                  url: '/home',
                },
              ],
            },
          ];
          routesConfig[0].children.push(...transListToTree(menuList, -1));
          console.log({ routesConfig }, JSON.stringify(routesConfig));
          loadRoutes(routesConfig);
          this.$message.success('登录成功');
          this.$router.push('/home');
        });
      } else {
        this.error = res.data.msg || '登录失败';
      }
    },
  },
};
</script>

<style lang="less" scoped>
.common-layout {
  background: url('~@/assets/img/bg.jpg') center center no-repeat;
  background-size: cover;

  .top {
    text-align: center;
    .header {
      height: 44px;
      line-height: 44px;
      a {
        text-decoration: none;
      }
      .logo {
        height: 44px;
        vertical-align: top;
        margin-right: 16px;
      }
      .title {
        font-size: 33px;
        color: @title-color;
        font-family: 'Myriad Pro', 'Helvetica Neue', Arial, Helvetica, sans-serif;
        font-weight: 600;
        position: relative;
        top: 2px;
        font-style: italic;
      }
    }
    .desc {
      font-size: 14px;
      color: @text-color-second;
      margin-top: 12px;
      margin-bottom: 40px;
    }
  }

  .login {
    width: 280px;
    margin: 120px auto 0;
    padding: 10px 20px;
    // background-color: rgba(207,220,226, 0.6);
    border-radius: 20px;

    @media screen and (max-width: 576px) {
      width: 95%;
    }
    @media screen and (max-width: 320px) {
      .captcha-button {
        font-size: 14px;
      }
    }
    .icon {
      font-size: 24px;
      color: @text-color-second;
      margin-left: 16px;
      vertical-align: middle;
      cursor: pointer;
      transition: color 0.3s;

      &:hover {
        color: @primary-color;
      }
    }
  }
}
</style>
